发布订阅是一种常见的设计模式,也成为观察者模式。它基于事件处理机制,允许多个观察者订阅某个事件,当时间被触发时,所有订阅该事件的观察者都会收到通知。
实现发布订阅的代码:
const PubSub = () => {
let subscribers = {};
//订阅事件
const subscribe = (eventName, callback) => {
if (!subscribers[eventName]) {
subscribers[eventName] = [];
}
subscribers[eventName].push(callback);
}
//发布事件
const publish = (eventName, ...args) => {
if (subscribers[eventName]) {
subscribers[eventName].forEach(callback => {
callback(...args);
})
}
}
//取消订阅
const unsubscribe = (eventName, callback) => {
if (subscribers[eventName]) {
subscribers[eventName] = subscribers[eventName].filter(cb => cb != callback);
}
}
return { subscribe, publish, unsubscribe };
}
//定义新的订阅发布
const pubSub1 = PubSub();
//定义订阅者怎样处理发布的信息
const click1 = (a, b) => {
console.log(a , b, 'click1')
}
const click2 = (a, b) => {
console.log(a , b, 'click2')
}
//将订阅者推到订阅者列表中
pubSub1.subscribe('click', click1);
pubSub1.subscribe('click', click2);
//发布click事件
pubSub1.publish('click', 1, 2);
//click1取消订阅click事件
pubSub1.unsubscribe('click', click1);
//发布click事件
pubSub1.publish('click', 1, 2);